<template>
  <div class="employees-container">
    <div class="app-container">

      <!-- 具体页面结构 -->
      <page-tools>
        <template #left>
          <span>本月: {{ total }}条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/employees/import')">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="hExport">导出excel</el-button>
          <el-button type="primary" size="small" @click="dialogVisible=true">新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top:20px">
        <el-table :data="employees">
          <el-table-column label="序号" type="index" :index="indexMethod" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template v-slot="{row}">
              <image-holder :src="row.staffPhoto" />
              <!-- <img class="avatar" :src="row.staffPhoto"> -->
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template v-slot="{row}">
              <!-- {{ row }} -->
              {{ formatEmployment(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable>
            <template v-slot="{row}">
              {{ formData(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{row}">
              <el-button type="text" @click="$router.push('/employees/detail/'+(row.id))">查看</el-button>
              <!-- <el-button type="text" @click="$router.push('/employees/detail?id='+(row.id))">查看</el-button> -->
              <el-button type="text" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" @click="hDel(row.id)">删除</el-button>
            </template>

          </el-table-column>
        </el-table>
        <el-dialog
          title="添加"
          :visible.sync="dialogVisible"
          width="50%"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          @closed="hClose"
        >
          <addor-edit ref="empDialog" @close="dialogVisible=false" @success="hSuccess" />
        </el-dialog>
        <el-dialog
          title="分配角色"
          :visible.sync="showDialogRole"
          width="50%"
          :close-on-press-escape="false"
          :close-on-click-modal="false"
          @closed="$refs.assignrole.resetIds()"
        >
          <assign-role
            :id="curId"
            ref="assignrole"
            @close="showDialogRole=false"
          />
        </el-dialog>
      </el-card>
      <el-pagination
        :current-page="q.page"
        :page-sizes="[5,10,15,20]"
        :page-size="q.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import employeesConst from '@/constant/employees'
import { delEmployee, getEmployees } from '@/api/employees'
import addorEdit from './emDialog.vue'
import dayjs from 'dayjs'

const hireTypeMap = {}
// 可选作业: 把 forEach 变成 reduce
// 执行循环后达成目标: { 1: '正式', 2: '非正式' }
employeesConst.hireType.forEach(item => {
  hireTypeMap[item.id] = item.value
})
export default {
  components: {
    addorEdit,
    AssignRole
  },
  data() {
    return {
      employees: [],
      total: 0,
      q: {
        page: 1,
        size: 5
      },
      dialogVisible: false,
      showDialogRole: false,
      curId: ''
    }
  },
  created() {
    this.loadEmployees()
  },
  methods: {
    indexMethod(index) {
      // console.log(index)
      const page = this.q.page
      const size = this.q.size
      return index + 1 + (page - 1) * size
    },

    async loadEmployees() {
      const res = await getEmployees(this.q)
      // console.log(res)
      this.employees = res.data.rows
      this.total = res.data.total
    },
    // 看hireType
    formatEmployment(code) {
      const result = employeesConst.hireType.find(item => item.id === code)
      if (result) {
        return result.value
      } else {
        return '未知'
      }
    },
    // 删除
    async hDel(id) {
      try {
        const res = await delEmployee(id)
        // console.log(res)
        this.$message.success(res.message)
        if (this.employees.length === 1 && this.q.page > 1) {
          this.q.page--
        }
        this.loadEmployees()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 情况表单
    hClose() {
      this.$refs.empDialog.resetForm()
    },
    hSuccess() {
      this.dialogVisible = false
      // 如果总条数取余当前页为0
      // 那么总条数就+1
      this.total++
      // +1的总条数除以当前页条数 比如 总十一条,除以第二页的五条,那么向上取整就为三,此时当前页面显示为三
      this.q.page = Math.ceil(this.total / this.q.size)
      this.loadEmployees()
    },
    formData(date) {
      return dayjs(date).format('YYYY-MM-DD')
    },
    handleSizeChange(size) {
      this.q.size = size
      this.loadEmployees()
    },
    handleCurrentChange(page) {
      this.q.page = page
      this.loadEmployees()
    },
    async hExport() {
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // 1. 发请求获取所有的数据
      const res = await getEmployees({ page: 1, size: this.total })
      // console.log(res)
      const list = res.data.rows

      // 遍历 list 找到每个元素, 将其属性名转为中文
      // const zhList = list.map(enObj => {
      //   const zhObj = {}
      //   const enKeys = Object.keys(enObj)
      //   enKeys.forEach(enKey => {
      //     const zhKey = mapInfo[enKey]
      //     zhObj[zhKey] = enObj[enKey]
      //   })
      //   return zhObj
      // })

      // 取第一个数据
      // const first = zhList[0]
      const first = list[0]
      if (!first) return
      // 取出 header
      const header = Object.keys(first).map(enKey => mapInfo[enKey])

      const data = list.map(item => {
        const code = item['formOfEmployment']
        item['formOfEmployment'] = hireTypeMap[code]
        return Object.values(item)
      })

      // 2. 导出 Excel (表头英文转中文)
      const excel = await import('@/vendor/Export2Excel')
      excel.export_json_to_excel({
        header, // 表头, 传入一个数组
        data, // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
        filename: '员工数据', // 导出的文件名称
        autoWidth: true, // 自适应宽度
        bookType: 'xlsx' // 文件类型
      })

      // import('@/vendor/Export2Excel').then(excel => {
      //   excel.export_json_to_excel({
      //     header: ['姓名', '职业'], // 表头, 传入一个数组
      //     data: [['黄陂威子', '推拿师'], ['刘谦', '魔术师'], ['刘狄威', 'Tony师傅']], // 数据, 传入一个二维数组 [ [] ] , 二维数组里面的数组就是一条数据
      //     filename: '黄陂在逃人员', // 导出的文件名称
      //     autoWidth: true, // 自适应宽度
      //     bookType: 'xlsx' // 文件类型
      //   })
      // })
    },
    hAssignRole(id) {
      // console.log(id)
      this.curId = id
      this.showDialogRole = true
      this.$nextTick(() => {
        this.$refs.assignrole.loadRoleIds()
      })
    }

  }
}

</script>
<style scoped>
.avatar{
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.el-pagination {
  height: 60px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
